<template>
    <div class="pjt-mt-report-create-view">

      <modules-title class="title-position" titleName="新增报告">

        <template slot="btn">
          <el-button plain @click="backClick" size="mini">返回</el-button>
          <el-button type="primary" size="mini" @click="confirm">提交</el-button>

        </template>

      </modules-title>

      <div class="pj-content">

        <el-form ref="form" :model="form" label-width="150px" style="width: 1200px" :rules="rules">
          <el-row style="display: flex;">
            <el-col :span="8">
              <el-form-item label="报告类型" prop="report_type">
                <el-select
                  v-model="form.report_type"
                  placeholder="请选择类型"
                  size="small"
                  @change="typeChange"
                >
                  <el-option label="周报" value="week"/>
                  <el-option label="月报" value="month"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="报告周期" v-if="form.report_type == 'week'" :prop="form.report_type == 'week' ? 'week' : 'aa'">
                <el-date-picker
                  v-model="form.week"
                  type="week"
                  format="yyyy 第 WW 周"
                  @change="weekChange"
                  placeholder="请选择周">
                </el-date-picker>
                <!--              <el-date-picker-->
                <!--                :clearable="false"-->
                <!--                v-model="form.weekValue"-->
                <!--                :format="'yyyy-MM 第' + form.week + '周'"-->
                <!--                @change="weekChange"-->
                <!--                value-format="yyyy-M-d"-->
                <!--                class="inp"-->
                <!--                size="medium"-->
                <!--                type="week"-->
                <!--                placeholder="请选择"-->
                <!--                :picker-options="{'firstDayOfWeek': 1}"-->
                <!--              ></el-date-picker>-->
              </el-form-item>

              <el-form-item label="报告月" v-else :prop="form.report_type != 'week' ? 'month' : 'aa'">
                <el-date-picker
                  @change="monthChange"
                  v-model="form.month"
                  type="month"
                  placeholder="请选择月">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属项目" prop="project_id">
                <el-select v-model="form.project_id" placeholder="请选择所属项目" filterable style="width: 100%" @change="projectChange" >
                  <el-option
                    v-for="item in projects"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>

          <el-form-item label="本周项目任务" v-if="form.report_type == 'week'">


<!--            <div v-for="(item,index) in list" :key="index" style="width: 100%;padding-bottom: 10px">-->
<!--              <el-row>-->
<!--                <el-col :span="8">-->
<!--                  <span>{{item.title}}</span>-->
<!--                </el-col>-->
<!--                <el-col :span="2">-->
<!--                  <span>{{item.status}}</span>-->
<!--                </el-col>-->
<!--                <el-col :span="2">-->
<!--                  <el-input v-model="item.progress" placeholder="请输入进度"></el-input>-->
<!--                </el-col>-->
<!--              </el-row>-->

<!--            </div>-->

            <el-table
              v-if="form.tasks.length"
              :data="form.tasks"
              border
            style="width: calc( 100% - 1px )">
              <el-table-column
                prop="task_name"
                align="center"
                label="任务名称">
              </el-table-column>
              <el-table-column
                prop="status"
                align="center"
                label="任务状态"
                width="200">
                <template slot-scope="scope">

                  <div v-if="scope.row.status == 0">未启动</div>
                  <div v-else-if="scope.row.status == 1">进行中</div>
                  <div v-else-if="scope.row.status == 2">暂停</div>
                  <div v-else-if="scope.row.status == 3">延期</div>
                  <div v-else-if="scope.row.status == 4">待验收</div>
                  <div v-else-if="scope.row.status == 5">验收不通过</div>
                  <div v-else-if="scope.row.status == 6">已完成</div>
                  <div v-else-if="scope.row.status == 7">已终止</div>

                  <div v-if="scope.row.delay_day" style="color: red">(延期{{scope.row.delay_day}}天)</div>
                </template>
              </el-table-column>
              <el-table-column
                label="任务进度"
                align="center"
                width="150">
                <template slot-scope="scope">
                  <div style="display: flex;align-items: center;justify-content: center" v-if="scope.row.status == 6">
                    100%
                  </div>
                  <div style="display: flex;align-items: center;justify-content: center" v-else-if="!scope.row.has_children && scope.row.person_in_charge.member_id == user_id && scope.row.status != 0">
                    <el-input v-model="scope.row.task_progress" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入任务进度" style="width: 80px;padding-right: 10px" @blur="inputBlur(scope.row)"></el-input><span>%</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>

          </el-form-item>

          <el-form-item :label="form.report_type == 'week' ? '本周工作计划' : '本月工作计划'">

            <span>{{form.plan?form.plan:"无"}}</span>

          </el-form-item>

          <el-form-item :label="form.report_type == 'week' ? '本周工作总结' : '本月工作总结'" prop="summary">

            <el-input
              clearable
              type="textarea"
              :rows="2"
              placeholder="请输入工作总结"
              v-model="form.summary">
            </el-input>

          </el-form-item>

          <el-form-item label="存在问题">

            <el-input
              clearable
              type="textarea"
              :rows="2"
              placeholder="请输入存在问题"
              v-model="form.problem">
            </el-input>

          </el-form-item>

          <el-form-item label="需协调和帮助" v-if="help.Enable" :prop="help.Required ? 'help' : 'aa'">

            <el-input
              clearable
              type="textarea"
              :rows="2"
              placeholder="请输入需协调和帮助"
              v-model="form.help">
            </el-input>

          </el-form-item>

          <el-form-item :label="form.report_type == 'week' ? '下周工作计划' : '下月工作计划'" v-if="plan.Enable" :prop="plan.Required ? 'next_plan' : 'aa'">

            <el-input
              clearable
              type="textarea"
              :rows="2"
              placeholder="请输入工作计划"
              v-model="form.next_plan">
            </el-input>

          </el-form-item>


          <el-form-item label="附件">
            <upload-select ref="upload" :edit-list="form.files" :project-data="{project_id: 'projectReport',validation: 1}" @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess"></upload-select>
<!--            <upload ref="upload" :edit-list="form.files" @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess" />-->
          </el-form-item>

        </el-form>

      </div>

    </div>
</template>

<script>

    import { reportSetting } from "@/api/report";

    export default {
        name: "index",
        data:function () {
            var validator = (rule, value, callback)=>{
                if (!value){
                    callback(new Error(this.form.report_type == "week" ? '请输入下周工作计划' : '请输入下月工作计划'))
                    return
                }
                callback()
            };

            return{
                user_id:'',
                projects:[],
                form:{
                    report_type:"week",
                    project_id:'',
                    project_name:'',
                    week:'',
                    weekValue:'',
                    tasks:[],
                    plan:'',
                    next_plan:'',
                    summary:'',
                    problem:'',
                    help:'',
                    files:[],
                    period:'',
                },
                isHelp:false,
                help:{},
                plan:{},

                list:[],

                rules: {
                    report_type: [
                        { required: true, message: '请选择报告类型', trigger: 'change' }
                    ],
                    project_id: [
                        { required: true, message: '请选择报告项目', trigger: 'change' }
                    ],
                    week: [
                        { type: 'date', required: true, message: '请选择周期', trigger: 'change' }
                    ],
                    month: [
                        { type: 'date', required: true, message: '请选择月', trigger: 'change' }
                    ],
                    summary: [
                        { required: true, message: '请输入总结', trigger: 'blur' }
                    ],
                    next_plan: [
                        { required: true, trigger: 'blur', validator:validator}
                    ],
                    help: [
                        { required: true, message: '请输入需协调和帮助', trigger: 'blur' }
                    ],
                    aa:[],
                }
            }
        },
        mounted:function(){

            this.user_id = this.$store.getters.userInfo.user.id
            //this.getProjectList();
            console.log(new Date().getTime())
            this.getsetting()
        },
        methods:{
            checkExist:function(){
                if (!this.form.period || !this.form.project_id){
                    return;
                }
                this.$api.PROJECT_START_WORK_REPORT_EXIST(this.form).then(res=>{
                    if (res.code == 200){
                        if (res.data && res.data == 1){
                            this.$message.error("项目报告已存在，请勿重复提交")
                        }
                    }else{
                        this.$message.error(res.code)
                    }
                })
            },
            //获取设置信息
            getsetting() {
                reportSetting(this.form.report_type).then((res) => {
                    if (res.code == 200) {
                        if (res.data){
                            res.data.fields.forEach(item=>{
                                if (item.Code == 'Help'){
                                    this.help = item;
                                    this.isHelp = item.Enable
                                }else if (item.Code == 'Plan'){
                                    this.plan = item;
                                }
                            })
                        }
                    }
                });
            },
            getProjectList:function(){
                let data = {
                    report_type:this.form.report_type,
                    period:this.form.period
                }
                this.$api.PROJECT_START_WORK_REPORT_PROJECT(data).then(res=>{
                    if (res.code == 200){

                        if (res.data.data){
                            res.data.data.forEach(item=>{
                                let phases = ""
                                if (item.project_phases_id == "1"){
                                    phases = "临床前研究"
                                }else{
                                    phases = "临床研究"
                                }
                                item.name = item.project_name + '(' + phases + ')'
                            })
                            this.projects = res.data.data;
                        }
                    }
                })
            },
            inputBlur:function(data){
                if (Number(data.task_progress) > 100){
                    data.task_progress = 100
                }
                data.task_progress = Number(data.task_progress)
                data.task_progress = Number(data.task_progress.toFixed(2))
            },
            backClick:function(){
                this.$router.back()
            },
            confirm:function () {
                if (this.form.period){
                    let date = new Date(this.form.period).getTime()
                    let date2 = new Date().getTime()

                    if (date > date2){
                        this.$message.error("请选择正确日期")
                        return
                    }
                }
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.$refs.upload.saveFile().then((dataList) => {
                            this.form.files = dataList[0]

                            this.$api.PROJECT_START_WORK_REPORT_CREATE(this.form).then(res=>{
                                if (res.code == 200){
                                    this.$route.params.refresh = true
                                    this.$router.back();
                                }else {
                                    this.$message.error(res.msg);
                                }
                            })
                        }).catch(err => {
                            console.log(err)
                        })

                    }
                });
            },
            typeChange:function () {
                this.form.project_name = ""
                this.form.project_name_id = ""
                this.form.tasks = [];

                this.$refs.form.clearValidate()
                this.getsetting()
            },
            deleteSuccess() {
                this.form.files = this.$refs.upload.emitFileList()
            },
            uploadSuccess() {
                this.form.files = this.$refs.upload.emitFileList()
            },
            monthChange:function(){

                this.form.period = this.dealDateStr(new Date(this.form.month)) + " 00:00:00";

                this.getProjectList();
                this.form.project_id = "";
                this.form.project_name = "";
                this.form.tasks = []
                // if (this.form.project_id){
                //     this.getLastReport();
                // }
            },
            // 初始化日期
            getDay() {
                var date = new Date();
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                if (month < 10) {
                    month = '0' + month;
                }
                if (day < 10) {
                    day = '0' + day;
                }
                let nowDay = year + '-' + month + '-' + day;
                this.form.week = this.getWeekInMonth(new Date(nowDay.replace(/-/g,'/')));
                this.form.weekValue = year + '-' + month + '-' + day;
            },
            projectChange:function(val){
                let index = this.projects.findIndex(a=>a.id == val)
                if (index != -1){
                    let data = this.projects[index];
                    this.form.project_id = data.id;
                    this.form.project_name = data.project_name;
                    if (this.form.report_type == "week"){
                        this.getTaksList(data.id)
                    }

                    if (this.form.period){
                        this.getLastReport();
                    }

                    this.checkExist();
                }
            },
            getTaksList:function (id){
                this.form.tasks = []
                this.$api.PROJECT_START_WORK_REPORT_TASK({project_id:id,period:this.form.period}).then(res=>{
                    if (res.code == 200){
                        console.log(res.data)
                        this.list = res.data.data;
                        this.form.tasks = res.data.data;
                    }
                }).catch(err=>{

                })
            },
            getLastReport:function(){
                let date = new Date(this.form.period).getTime()
                let time = 60 * 60 * 24 * 1000 * 7

                let date2 = new Date(date-time)
                let dateStr = this.dealDateStr(date2) + " 00:00:00"

                let data = {
                    report_type:this.form.report_type,
                    period:dateStr,
                    project_id:this.form.project_id
                }
                this.$api.PROJECT_START_WORK_REPORT_LAST_DETAIL(data).then(res=>{
                    if (res.code == 200){
                        if (res.data){
                            this.form.plan = res.data.next_plan
                        }else {
                            this.form.plan = ''
                        }
                    }
                })
            },
            weekChange(val) {
                // if (val) {
                //     let arr = val.split('-');
                //     this.form.week = this.getWeekInMonth(new Date(val));
                // }

                this.form.period = this.dealDateStr(new Date(this.form.week)) + " 00:00:00";

                this.getProjectList();
                this.form.project_id = "";
                this.form.project_name = "";
                this.form.tasks = []
            },
            dealDateStr:function(date){
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                return year + "-" + month + "-" + day
            },
            // 根据日期判断是月的第几周
            getWeekInMonth(t) {
                if (t == undefined || t == '' || t == null) {
                    t = new Date();
                } else {
                    var _t = new Date();
                    _t.setYear(t.getFullYear());
                    _t.setMonth(t.getMonth());
                    _t.setDate(t.getDate());

                    var date = _t.getDate(); //给定的日期是几号

                    _t.setDate(1);
                    var d = _t.getDay(); //1. 得到当前的1号是星期几。
                    var fisrtWeekend = d;
                    if (d == 0) {
                        fisrtWeekend = 1;
                        //1号就是星期天
                    } else {
                        fisrtWeekend = 7 - d + 1; //第一周的周未是几号
                    }
                    if (date <= fisrtWeekend) {
                        return 1;
                    } else {
                        return 1 + Math.ceil((date - fisrtWeekend) / 7);
                    }
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
  @import "@/assets/scss/views/projectManagement/report/create.scss";
</style>
